package zmee.bid.opplugin;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.alibaba.excel.util.ObjectUtils;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.form.CloseCallBack;
import kd.bos.form.ShowType;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.events.BeforeDoOperationEventArgs;
import kd.bos.form.events.ClosedCallBackEvent;
import kd.bos.form.field.BasedataEdit;
import kd.bos.form.field.events.BeforeF7SelectEvent;
import kd.bos.form.field.events.BeforeF7SelectListener;
import kd.bos.form.operate.AbstractOperate;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.scm.common.util.SrmCommonUtil;
import kd.scm.pds.common.util.OpenFormUtils;

import java.util.*;

/**
* @author lijiawang
* @Date 2023/1/5 16:02
* @Description:开标准备获取评委
*/
public class SrcBidopenOperation extends AbstractFormPlugin implements BeforeF7SelectListener {

    @Override
    public void registerListener(EventObject e) {
        BasedataEdit listingBudgetItem = this.getView().getControl("judgeuser");
        listingBudgetItem.addBeforeF7SelectListener(this);
    }

    @Override
    public void beforeDoOperation(BeforeDoOperationEventArgs args) {
        String operateKey = ((AbstractOperate)args.getSource()).getOperateKey();
        if(operateKey.equals("selectexpert")){
            selectExpert();
        } else if ("submit".equals(operateKey)) {
            DynamicObject sourcetype = (DynamicObject) this.getModel().getValue("sourcetype");
            if (null != sourcetype) {
                String number = sourcetype.getString("number");
                DynamicObjectCollection judgeuser = (DynamicObjectCollection) this.getModel().getValue("judgeuser");
                if ("C010405".equals(number)) {
                    if (judgeuser.isEmpty() || judgeuser.size() < 5 || judgeuser.size() % 2 == 0) {
                        this.getView().showTipNotification("当【采购方式】是”公开招标“时,抽取专家人数必须大于等于5的奇数!");
                        args.setCancel(true);
                    }
                } else {
                    if (judgeuser.isEmpty() || judgeuser.size() < 3 || judgeuser.size() % 2 == 0) {
                        this.getView().showTipNotification("当【采购方式】不是”公开招标“时,抽取专家人数必须大于等于3的奇数!");
                        args.setCancel(true);
                    }
                }
            } else {
                this.getView().showTipNotification("请先选择”采购方式“！");
                args.setCancel(true);
            }
        }
    }

    @Override
    public void afterDoOperation(AfterDoOperationEventArgs args) {
        String key = args.getOperateKey();
        if("save".equals(key)) {
            DynamicObject sourcetype = (DynamicObject) this.getModel().getValue("sourcetype");
            switch (sourcetype.getString("number")) {
                case"C010406":
                case"C010418":
                                break;
                default:
                String billno = this.getModel().getValue("billno").toString();
                DynamicObject[] loads = BusinessDataServiceHelper.load("src_bidopenconfig", "id,scorer", new QFilter("package.project.billno", QCP.equals, billno).toArray());
                List<String> list = new ArrayList();
                for (int j = 0; j < loads.length; j++) {
                    DynamicObjectCollection scorer = loads[j].getDynamicObjectCollection("scorer");
                    for (int k = 0; k < scorer.size(); k++) {
                        list.add(scorer.get(k).getString("fbasedataid.id"));
                        list.add(scorer.get(k).getString("fbasedataid.id"));
                    }
                }
                Object[] currencyIds = new Object[list.size()];
                for (int j = 0; j < list.size(); j++) {
                    currencyIds[j] = list.get(j);
                }
                this.getModel().setValue("judgeuser", currencyIds);
                break;
            }
        } else if ("audit".equals(key)) {
            Object supervision = this.getModel().getValue("zmee_supervision");
            if (!ObjectUtils.isEmpty(supervision)) {
                Object id = this.getModel().getValue("id");
                QFilter filter = new QFilter("parentid", "=", id);
                DynamicObject object = BusinessDataServiceHelper.loadSingle("src_project_man", "id,entryentity,entryentity.bizrole," +
                        "entryentity.bidder", filter.toArray());
                DynamicObjectCollection entryentity = object.getDynamicObjectCollection("entryentity");
                for (DynamicObject dynamicObject : entryentity) {
                    DynamicObject bizrole = dynamicObject.getDynamicObject("bizrole");
                    String number = bizrole.getString("number");
                    if ("SYS022".equals(number)) {
                        DynamicObject objects = (DynamicObject) supervision;
                        dynamicObject.set("bidder", objects.get("id"));
                    }
                }
                SaveServiceHelper.save(new DynamicObject[]{object});
            }
        }
    }

    private void selectExpert() {
        DynamicObject projectObj = this.getModel().getDataEntity();
        long projectId = SrmCommonUtil.getPkValue(projectObj);
        Map<String, Object> paramMap = new HashMap(16);
        paramMap.put("project", projectId);
        paramMap.put("currentrow", "0");
        paramMap.put("packageid", "0");
        paramMap.put("packagename", null);
        paramMap.put("indextypeid", "0");
        OpenFormUtils.openDynamicPage(this.getView(), "pds_selectexpert", ShowType.MainNewTabPage, paramMap, new CloseCallBack(this, "pds_selectexpert"));

    }

    @Override
    public void closedCallBack(ClosedCallBackEvent backEvent) {
        Object returnData = backEvent.getReturnData();
        String actionId = backEvent.getActionId();
        switch (actionId){
            case "pds_selectexpert":
                if(returnData!=null) {
                    //String returnData = backEvent.getReturnData().toString();
                    JSONObject jsonObject = new JSONObject(returnData.toString());
                    JSONArray list = jsonObject.getJSONArray("expertuser");
                    Object [] currencyIds = new Object [list.size()];
                    for (int j = 0; j < list.size(); j++) {
                        currencyIds [j] = list.get(j);
                    }
                    this.getModel().setValue("judgeuser",currencyIds);
                }
                break;
        }
    }

    @Override
    public void afterBindData(EventObject e) {
        IDataModel model = this.getModel();
        Object supervision = model.getValue("zmee_supervision");
        String billStatus = (String) model.getValue("billstatus");
        if (!ObjectUtils.isEmpty(supervision) && !Objects.equals(billStatus, "A")) {
            return;
        }
        Object id = model.getValue("id");
        QFilter filter = new QFilter("parentid", "=", id);
        DynamicObject object = BusinessDataServiceHelper.loadSingle("src_project_man", "id,entryentity,entryentity.bizrole," +
                "entryentity.bidder", filter.toArray());
        DynamicObjectCollection entryentity = object.getDynamicObjectCollection("entryentity");
        for (DynamicObject dynamicObject : entryentity) {
            DynamicObject bizrole = dynamicObject.getDynamicObject("bizrole");
            String number = bizrole.getString("number");
            if ("SYS022".equals(number)) {
                model.setValue("zmee_supervision", dynamicObject.get("bidder"));
            }
        }

        //Object time = this.getModel().getValue("time");
        //if (time == null) {
        //    Object stopBidDate = this.getModel().getValue("stopbiddate");
        //    this.getModel().setValue("time", stopBidDate);
        //}
    }

    @Override
    public void beforeF7Select(BeforeF7SelectEvent event) {
        String name = event.getProperty().getName();
        if("judgeuser".equals(name)){
            DynamicObject[] loads = BusinessDataServiceHelper.load("src_expert", "id,user", new QFilter("1", QCP.equals, "1").toArray());
            String[] ids=new String[loads.length];
            for (int i = 0; i < loads.length; i++) {
                ids[i]=loads[i].getString("user.id");
            }
            List<QFilter> list=new ArrayList<>();
            QFilter qFilter=new QFilter("id", QCP.in,ids);
            list.add(qFilter);
            event.setCustomQFilters(list);
        }
    }
}
